<?php

	if(!class_exists('Database', false))
	{
		require_once CLASS_PATH . 'Database.class.php';
	}
	
	class User
	{
		public $id;
		public $name;
		public $email_address;
		public $role_id;
		public $active;

		private $db;
		
		public function __construct()
		{
			global $_DATASOURCE;
			$this->db = $_DATASOURCE;
			$this->init();
		}
		
		public function init()
		{
			$this->deauthorize();

			if( isset($_COOKIE[SESSION_COOKIE_NAME]) )
			{
				$session_user = $this->authorize_by_session( $_COOKIE[SESSION_COOKIE_NAME] );
				
				foreach( $session_user as $property => $value )
				{
					$this->$property = $value;
				}				
			}
		}

		public function deauthorize()
		{
			$this->id = 0;
			$this->name = 'Guest User';
			$this->email = 'guest@'.$_SERVER['REMOTE_ADDR'];
			$this->role_id = 0;
			$this->active = 1;		
		}
		
		public function authorize( $email, $password, $session_id )
		{
			$sql = sprintf( "select * from users where email = '%s' and password = '%s'", $email, sha1($password) );
			$results = $this->db->default->select( $sql );	
			
			if( count($results)!=0 )
			{
				$this->id = $results[0]['id'];
			}
						
			$sql = sprintf( "update sessions set user_id = %d where session_id = '%s'", $this->id, $session_id );	
			$results = $this->db->default->update( $sql );	
			
			return $user_id;
		}

		public function get_access_level( $app_id )
		{
			// $db = new Database;
		
			// if($this->role_id == 1){ return 100; }
			// else if($this->role_id == 2){ return 50; }
			// else if($this->role_id == 3){ return 0; }	
			// else
			// {
				// $sql = sprintf("select IFNULL(rd.access_level, 0) as access_level from {$db->prefix}_role_definitions rd where rd.role_id = %s and rd.application_id = '%s'", $role_id, $app_id);
				// $temp = $db->select($sql, true);
				// return $temp['access_level'];
			// }
		}
		
		private function authorize_by_session( $session_id )
		{
			$sql = sprintf( "select user_id from sessions where session_id = '%s' and expire_time > %d", $session_id, date('U') );
			$results = $this->db->default->select( $sql, true );	
			if( count($results)!=0 )
			{
				return $this->user_info( $results['user_id'] );
			}
			else
			{
				return array();
			}
		}
		
		private function user_info( $user_id )
		{
			$sql = sprintf( "select * from users where id = '%s'", $user_id );
			$results = $this->db->default->select( $sql, true );	

			if( count($results)!=0 )
			{
				return $results;
			}
			else
			{
				return array();
			}
		}
		
	}
?>
